package com.weiyuwqj.server.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.weiyuwqj.api.util.IpUtils;
import com.weiyuwqj.api.util.JwtUtils;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;

@Component
public class SimpleCORSFilter implements Filter {
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    String key="RskqNRL0WSwwVYFbGWfu54/wNPdD0I1N9u+e1PbTZO3zbk/LV95JvePbewf4QPYmqJ9WG9zpLXvZ" +
            "kgK3nf4eXw==MGVlOWQzZWUtZGRkYy00YTNkLTgzZjEtNTgyNWVmZWFmNDk0";
    
    HttpServletRequest request=(HttpServletRequest)req;
    HttpServletResponse response=(HttpServletResponse)res;
    IpUtils.set(request);

    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Allow-Methods", "POST,OPTIONS");
    response.setHeader("Access-Control-Max-Age", "3600");
    response.setHeader("Access-Control-Allow-Headers",
            "optional-header,x-requested-with,x-access-token,x-access-appid,Content-Type");
    if(request.getMethod().equals("OPTIONS")){
      response.setStatus(200);
      return;
    }
    String path=request.getServletPath();
    if(!path.equals("/server/authorize")){
      String token = request.getHeader("x-access-token");
      String appid = request.getHeader("x-access-appid");
      String info="";
      if(appid!=null){
        if(token!=null){
          try{
            info=JwtUtils.verify(token,key);
          }catch (Exception e){
            e.printStackTrace();
          }
        }
        if(info==null||info.isEmpty()){
          response.setContentType("application/json;charset=UTF-8");
          response.setHeader("Pragma", "No-cache");
          response.setHeader("Cache-Control", "no-cache");
          response.setDateHeader("Expires", 0);
          response.setStatus(401);
          PrintWriter out =response.getWriter();
          ObjectMapper mapper=new ObjectMapper();
          HashMap<String,Object> msg=new HashMap<String,Object>();
          msg.put("result","fail");
          msg.put("messageCode","sys.sessionTimeout");
          String json=mapper.writeValueAsString(msg);
          out.print(json);
          out.flush();
          out.close();
          return;
        }
      }
    }


    chain.doFilter(req, res);
    IpUtils.clear();
  }
  public void init(FilterConfig filterConfig) {}
  public void destroy() {}




}